package com.ct.ecommerce.uc.service;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.ct.ecommerce.api.uc.client.AccountService;
import com.ct.ecommerce.api.uc.dto.AccountDTO;
import com.ct.ecommerce.framework.core.BeanCopierUtils;
import com.ct.ecommerce.uc.dao.entity.AccountEntity;
import com.ct.ecommerce.uc.dao.mapper.AccountMapper;
import com.google.common.base.Preconditions;
import io.seata.spring.annotation.GlobalLock;
import java.math.BigDecimal;
import javax.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author changtong
 * @since 2021/5/26
 */
@DubboService
@Slf4j
public class AccountServiceImpl implements AccountService {


    @Resource
    private AccountMapper accountMapper;

    @Override
    public AccountDTO findUserAccount(Long userId) {
        AccountEntity accountEntity = accountMapper.selectById(userId);
        Preconditions.checkNotNull(accountEntity, "用户不存在");
        return BeanCopierUtils.copyProperties(accountEntity, AccountDTO.class);
    }

    @Override
    public void deductAccountAmount(Long userId, BigDecimal amount) {
        AccountEntity accountEntity = accountMapper.selectById(userId);
        Preconditions.checkNotNull(accountEntity, "用户不存在");
        if (accountEntity.getAmount().compareTo(amount) < 0) {
            throw new IllegalArgumentException("用户金额不足。。");
        }
        BigDecimal balance = accountEntity.getAmount().subtract(amount);

        LambdaUpdateWrapper<AccountEntity> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(AccountEntity::getUserId, userId)
            .set(AccountEntity::getAmount, balance);
       accountMapper.update(null, updateWrapper);

    }
}
